package com.example.demoreptile;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
 
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
 
public class Demo03 {
	public static void main(String[] args) {
		try {
			URL imageUrl = new URL("https://movie.douban.com/");
			HttpURLConnection connect = (HttpURLConnection)imageUrl.openConnection();
			
			connect.setRequestMethod("GET");
			connect.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36 Edg/103.0.1264.62");
			System.out.println("HTTP的连接类型是" + connect.getClass());
			try (BufferedReader br = new BufferedReader(
					new InputStreamReader(connect.getInputStream(), StandardCharsets.UTF_8));) {
				String line = null;
				while ((line = br.readLine()) != null) {
					line =line.trim();
					
					if(line.startsWith("<img")&&line.contains("https://img")&&line.contains(".jpg")) {
						String src="",alt="";
						//使用jsoup解析html 
						//document类包含解析html中的所有标签
						//elements若干元素elements形成的集合（继承 ArrayList）
						//element包含某一个html元素
						Document doc = Jsoup.parse(line);
						Element imgelElement = doc.getElementsByTag("img").first();
						//获取img中的src和alt属性
						src=imgelElement.attr("src");
						alt=imgelElement.attr("alt");
			
						URL url = new URL(src);
						HttpURLConnection imageUrlconnection = (HttpURLConnection)url.openConnection();// 读取图片
						try (BufferedInputStream bis = new BufferedInputStream(imageUrlconnection.getInputStream());
								BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\data\\movie\\"+alt+".jpg"));){
							byte[] buff = new byte[1024];//边读边写
							int len = -1;
							while((len=bis.read(buff))!=-1) {
								bos.write(buff,0,len);
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
}
}